package com.todo.event.activity.infrastructure.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.common.utils.MathUtils;
import com.todo.common.utils.StringUtils;
import com.todo.event.activity.common.enums.EventDetailStatusEnum;
import com.todo.event.activity.infrastructure.convert.EventActivityConvert;
import com.todo.event.activity.infrastructure.entity.condition.EventInfoCondition;
import com.todo.event.activity.infrastructure.entity.domain.EventDetailDO;
import com.todo.event.activity.infrastructure.entity.po.EventFieldInfoPO;
import com.todo.event.activity.infrastructure.entity.po.EventInfoPO;
import com.todo.event.activity.infrastructure.mapper.EventFieldInfoMapper;
import com.todo.event.activity.infrastructure.mapper.EventInfoMapper;
import com.todo.event.activity.infrastructure.repository.EventDetailRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author azhebuxing
 * @date 2025/1/7 09:26
 * @description
 */
@Slf4j
@Repository
public class EventDetailRepositoryImpl implements EventDetailRepository {

    @Resource
    private EventInfoMapper eventInfoMapper;
    @Resource
    private EventFieldInfoMapper eventFieldInfoMapper;

    @Override
    @Transactional
    public Boolean insertEventDetail(EventDetailDO eventDetailDO) {
        if (eventDetailDO == null || eventDetailDO.getEventCode() == null || eventDetailDO.getEventInfo() == null || eventDetailDO.getEventFieldList() == null) {
            return false;
        }
        EventDetailDO alreadyEventDetailDO = queryEventDetailByCode(eventDetailDO.getEventCode());
        if (alreadyEventDetailDO != null) {
            return false;
        }
        EventInfoPO eventInfoPO = EventActivityConvert.buildEventInfoPO(eventDetailDO);
        int infoInsert = eventInfoMapper.insertEventInfoPO(eventInfoPO);
        if (infoInsert != 1) {
            log.error("EventDetailRepository#insertEventDetail 新增事件详情失败，保存基本信息失败 eventDetailDO：【{}】", JSONObject.toJSONString(eventDetailDO));
            return false;
        }
        List<EventFieldInfoPO> eventFieldInfoPOList = EventActivityConvert.buildEventFieldInfoPOList(eventDetailDO);
        int insertBatch = eventFieldInfoMapper.insertBatch(eventFieldInfoPOList);
        if (insertBatch == 0) {
            log.error("EventDetailRepository#insertEventDetail 新增事件详情失败，保存字段关联异常 eventDetailDO：【{}】", JSONObject.toJSONString(eventDetailDO));
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    public EventDetailDO queryEventDetail(Long id) {
        if (id == null) {
            return null;
        }
        EventInfoPO eventInfoPO = eventInfoMapper.queryEventInfoPOById(id);
        if (eventInfoPO == null) {
            return null;
        }
        List<EventFieldInfoPO> eventFieldInfoPOS = eventFieldInfoMapper.queryListByEventCode(eventInfoPO.getEventCode());
        return EventActivityConvert.buildEventDetailDO(eventInfoPO, eventFieldInfoPOS);
    }

    @Override
    public EventDetailDO queryEventDetailByCode(String eventCode) {
        if (StringUtils.isBlank(eventCode)) {
            return null;
        }
        EventInfoPO eventInfoPO = eventInfoMapper.queryEventInfoByCode(eventCode);
        if (eventInfoPO == null) {
            return null;
        }
        List<EventFieldInfoPO> eventFieldInfoPOS = eventFieldInfoMapper.queryListByEventCode(eventCode);
        return EventActivityConvert.buildEventDetailDO(eventInfoPO, eventFieldInfoPOS);
    }

    @Override
    public Boolean checkEventNameExist(String eventName) {
        if (StringUtils.isBlank(eventName)) {
            return true;
        }
        EventInfoPO eventInfoPO = eventInfoMapper.queryEventInfoPOByName(eventName);
        return eventInfoPO != null;
    }

    @Override
    @Transactional
    public Boolean updateEventDetail(EventDetailDO eventDetailDO) {
        if (eventDetailDO == null || eventDetailDO.getId() == null || eventDetailDO.getEventCode() == null) {
            return false;
        }
        EventInfoPO eventInfoPO = EventActivityConvert.buildEventInfoPO(eventDetailDO);
        int updateInfo = eventInfoMapper.updateEventInfoPOById(eventInfoPO);
        if (updateInfo != 1) {
            log.error("EventDetailRepository#updateEventDetail 更新事件详情失败，保存基本信息失败 eventDetailDO：【{}】", JSONObject.toJSONString(eventDetailDO));
            return false;
        }
        int removeFields = eventFieldInfoMapper.removeEventFieldByEventCode(eventDetailDO.getEventCode());
        if (removeFields == 0) {
            log.error("EventDetailRepository#updateEventDetail 更新事件详情失败，删除字段关联异常 eventDetailDO：【{}】", JSONObject.toJSONString(eventDetailDO));
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        List<EventFieldInfoPO> eventFieldInfoPOList = EventActivityConvert.buildEventFieldInfoPOList(eventDetailDO);
        int insertBatch = eventFieldInfoMapper.insertBatch(eventFieldInfoPOList);
        if (insertBatch == 0) {
            log.error("EventDetailRepository#updateEventDetail 更新事件详情失败，保存字段关联异常 eventDetailDO：【{}】", JSONObject.toJSONString(eventDetailDO));
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean removeEventDetailById(Long id) {
        if (id == null || id < 0) {
            return true;
        }
        EventInfoPO eventInfoPO = eventInfoMapper.queryEventInfoPOById(id);
        if (eventInfoPO == null) {
            log.info("EventDetailRepository#removeEventDetailById 删除事件详情完成，事件不存在，默认成功 id：【{}】", id);
            return true;
        }
        int infoRemove = eventInfoMapper.removeEventInfoPOById(id);
        if (infoRemove != 1) {
            return false;
        }
        int fieldRemove = eventFieldInfoMapper.removeEventFieldByEventCode(eventInfoPO.getEventCode());
        if (fieldRemove == 0) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    public PageResult<EventInfoPO> queryEventInfoPageByCondition(EventInfoCondition eventInfoCondition) {
        PageResult<EventInfoPO> pageResult = new PageResult<>();
        if (eventInfoCondition == null) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        pageResult.setPageNum(eventInfoCondition.getPageIndex());
        pageResult.setPageSize(eventInfoCondition.getPageSize());
        long count = eventInfoMapper.queryCountByCondition(eventInfoCondition);
        if (count <= 0) {
            log.info("EventDetailRepository#queryEventInfoPageByCondition 事件数据查询完成，总数为空 eventInfoCondition：【{}】", JSONObject.toJSONString(eventInfoCondition));
            return pageResult;
        }
        pageResult.setPageCount((int) MathUtils.divide(count, eventInfoCondition.getPageSize()));
        pageResult.setTotal(count);
        List<EventInfoPO> eventInfoPOList = eventInfoMapper.queryEventInfoListByCondition(eventInfoCondition);
        if (CollectionUtils.isEmpty(eventInfoPOList)) {
            pageResult.setHasNext(false);
            log.info("EventDetailRepository#queryEventInfoPageByCondition 事件数据查询完成，查询结果数据为空 eventInfoCondition：【{}】", JSONObject.toJSONString(eventInfoCondition));
            return pageResult;
        }
        pageResult.setResults(eventInfoPOList);
        pageResult.setCurrentIndex(eventInfoPOList.get(0).getId());
        pageResult.setHasNext(eventInfoPOList.size() >= eventInfoCondition.getPageSize());
        return pageResult;
    }

    @Override
    public Boolean updateEventDetailStatus(Long id, EventDetailStatusEnum oldStatus, EventDetailStatusEnum newStatus) {
        if (id == null || oldStatus == null || newStatus == null) {
            return false;
        }
        return eventInfoMapper.updateEventInfoStatus(id, oldStatus.getType(), newStatus.getType()) > 0;
    }

    @Override
    public List<EventDetailDO> queryEventDetailByTopic(String topicName, String tag) {
        if (StringUtils.isBlank(topicName) || StringUtils.isBlank(tag)) {
            return Collections.emptyList();
        }
        List<EventInfoPO> eventInfoPOList = eventInfoMapper.queryEventInfoByTopic(topicName, tag, EventDetailStatusEnum.RUNNING.getType());
        if (CollectionUtils.isEmpty(eventInfoPOList)) {
            return Collections.emptyList();
        }
        List<EventDetailDO> eventDetailDOList = new ArrayList<>();
        for (EventInfoPO eventInfoPO : eventInfoPOList) {
            List<EventFieldInfoPO> eventFieldInfoPOList = eventFieldInfoMapper.queryListByEventCode(eventInfoPO.getEventCode());
            EventDetailDO eventDetailDO = EventActivityConvert.buildEventDetailDO(eventInfoPO, eventFieldInfoPOList);
            eventDetailDOList.add(eventDetailDO);
        }
        return eventDetailDOList;
    }
}
